// pages/category/category.js
import { 
  getCategory,
  getSubcategory,
  getCategoryDetail
}from "../../service/category";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    categories: [],
    categoryData: {},
    currentIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getData()
  },

  /**
   * 自定义私有函数
   */
  _getData() {
    this._getCategory()
  },
  _getCategory() {
    getCategory().then(res => {
      // 1. 获取 categories
      console.log(res.data.data.category.list);
      const categories = res.data.data.category.list
      // 2. 初始化每个类别的子数据
      const categoryData = {}
      for (let i = 0;i < categories.length;i++){
        categoryData[i] = {
          subcategories: [],
          categoryDetail: []
        }
      }
      // 3. 修改data中的数据
      this.setData({
        categories: res.data.data.category.list,
        categoryData
      })
      // 4. 请求第一个类别的数据
      this._getSubcategory(0)
      // 5. 请求第一个类别的详情数据
      this._getCategoryDetail(0)
    })
  },
  /**
   * 自定义私有函数
   */
  _getSubcategory(currentIndex) {
    // 1. 获取对应的maitKey
    const maitKey = this.data.categories[currentIndex].maitKey
    console.log(maitKey);
    // 2. 请求的数据
    getSubcategory(maitKey).then(res => {
      // console.log(res.data.data.list);
      const tempCategoryData = this.data.categoryData
      tempCategoryData[currentIndex].subcategories = res.data.list
      this.setData({
        categoryData: tempCategoryData
      })
    })
  },
  _getCategoryDetail(currentIndex) {
    // 1. 获取对应的miniWallKey
    const miniWallKey = this.data.categories[currentIndex].miniWallkey
    // console.log(miniWallKey);
    // 2. 请求数据类别的数据
    this._getRealCategoryDetail(currentIndex, miniWallKey, 'pop')
    // this._getRealCategoryDetail(currentIndex, miniWallKey, 'new')
    // this._getRealCategoryDetail(currentIndex, miniWallKey, 'sell')
  },
  _getRealCategoryDetail(index, miniWallKey, type) {
    getCategoryDetail(miniWallKey, type).then(res => {
      // 1. 获取categoryData
      const categoryData = this.data.categoryData
      // 2. 修改数据
      categoryData[index].categoryDetail = res.data
      // console.log(res);
      // 3. 修改data中的数据
      this.setData({
        categoryData
      })
    })
  },
  menuClick(e) {
    // 1. 改变当前的currentIndex
    const currentIndex = e.detail.currentIndex
    this.setData({
      currentIndex
    })
    // 2. 请求对应的currentIndex的数据
    this._getSubcategory(currentIndex)
    // 3. 请求对应的currentIndex的详情数据
    this._getCategoryDetail(currentIndex)
  }
})